package com.szgr.baoyin;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.baidu.trace.LBSTraceClient;
import com.baidu.trace.OnStartTraceListener;
import com.baidu.trace.OnStopTraceListener;
import com.baidu.trace.Trace;
import com.szgr.baoyin.activity.SearchActivity;
import com.szgr.baoyin.fragment.CustomerServiceFragment;
import com.szgr.baoyin.fragment.HomePageFragment1029;
import com.szgr.baoyin.fragment.PersonalFragment;
import com.szgr.baoyin.fragment.PersonalFragment1203;
import com.szgr.baoyin.fragment.ReduceFragment;
import com.szgr.baoyin.fragment.ServiceStationFragment;
import com.szgr.baoyin.interfaces.PersonalInterface;
import com.szgr.baoyin.model.BYFragment;
import com.szgr.baoyin.server.fragment.ServerEvaluateFragment;
import com.szgr.baoyin.server.fragment.ServerMessageFragment;
import com.szgr.baoyin.server.fragment.ServerPersonalFragment;
import com.szgr.baoyin.server.fragment.ServerTaskFragment;
import com.szgr.baoyin.utils.SystemBarTintManager;
import com.szgr.baoyin.utils.ToastUtils;
import com.umeng.update.UmengUpdateAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener,PersonalInterface, View.OnClickListener {

    private FrameLayout mContainer;
    private List<BYFragment> mFragments;
    private RadioGroup mRadioGroup;
    private FragmentManager mFragmentManager;
    private RadioButton rb_home;
    private RadioButton rb_server;
    private RadioButton rb_custom;
    private RadioButton rb_my;
    private int backFlag = 0;
    private int topHeight;
    private int bottomHeight;
//    private HomePageInterface hpi;
    private LinearLayout searchTop;
    private EditText et_search;
    private SystemBarTintManager mTintManager;
    private int newPos = -1;
    private int oldPos;
    private LBSTraceClient client;
    private Trace trace;

    private HomePageFragment1029 firstFrag;
    private ReduceFragment secondFrag;
    private CustomerServiceFragment thirdFrag;
    private PersonalFragment1203 fourthFrag;
    private List<Fragment> fragments;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        UmengUpdateAgent.setUpdateOnlyWifi(false);//是否仅在wifi模式下提醒
        UmengUpdateAgent.update(this);

        //判断操作系统的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 状态栏透明 需要在创建SystemBarTintManager之前调用。
            setTranslucentStatus(true);//方法如下
        }
        mTintManager = new SystemBarTintManager(this);
        // 设置状态栏背景
        mTintManager.setStatusBarTintEnabled(true);
        mTintManager.setStatusBarTintResource(R.color.main_blue);//颜色可以随便修改

        initView();
    }

    private void initView() {
        mContainer = (FrameLayout) findViewById(R.id.main_container);

        rb_home = (RadioButton) findViewById(R.id.rb_home_page);
        rb_server = (RadioButton) findViewById(R.id.rb_service_station);
        rb_custom = (RadioButton) findViewById(R.id.rb_customer_service);
        rb_my = (RadioButton) findViewById(R.id.rb_personal);

        mRadioGroup = (RadioGroup) findViewById(R.id.main_radio_group);
        mRadioGroup.setOnCheckedChangeListener(this);
        mFragments = new ArrayList<>();

            firstFrag = new HomePageFragment1029();
            secondFrag = new ReduceFragment();
            thirdFrag = new CustomerServiceFragment();
            fourthFrag = new PersonalFragment1203();


        if(MyApplication.getmInstance().isClient()) {
            //初始化四个片段
//            mFragments.add(new HomePageFragment1029());
//            mFragments.add(new ServiceStationFragment());
//            mFragments.add(new CustomerServiceFragment());
//            mFragments.add(new PersonalFragment());
//            hpi = (HomePageInterface) mFragments.get(0);
        }else{
            //初始化服务端四个片段
//            mFragments.add(new ServerMessageFragment());
//            mFragments.add(new ServerTaskFragment());
//            mFragments.add(new ServerEvaluateFragment());
//            mFragments.add(new ServerPersonalFragment());
        }

        mFragmentManager = getSupportFragmentManager();
        fragments = new ArrayList<>();
//        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
//        fragmentTransaction.add(R.id.main_container,firstFrag,"first");
//        fragmentTransaction.add(R.id.main_container,secondFrag,"second");
//        fragmentTransaction.add(R.id.main_container,thirdFrag,"third");
//        fragmentTransaction.add(R.id.main_container,fourthFrag,"fourth");
//        fragmentTransaction.commitAllowingStateLoss();


        searchTop = (LinearLayout) findViewById(R.id.search_top);
        searchTop.measure(0, 0);
        mRadioGroup.measure(0,0);
        topHeight = searchTop.getMeasuredHeight();
        bottomHeight = mRadioGroup.getMeasuredHeight();
        System.out.println("------main------->" + "top:" + topHeight + ",bottom:" + bottomHeight);
        //默认选中第一个
        ((RadioButton)mRadioGroup.getChildAt(0)).setChecked(true);
//        replaceFragment(mFragments.get(0));

        TextView tv_search = (TextView) findViewById(R.id.home_page_search);
        tv_search.setOnClickListener(this);
        et_search = (EditText) findViewById(R.id.main_search);

//        //实例化轨迹服务客户端
//        client = new LBSTraceClient(getApplicationContext());
//        //鹰眼服务ID
//        long serviceId  = 104174;
//        //entity标识
//        String entityName = MyApplication.getmInstance().getUsername() + System.currentTimeMillis() + "";
//        //轨迹服务类型（0 : 不上传位置数据，也不接收报警信息； 1 : 不上传位置数据，但接收报警信息；2 : 上传位置数据，且接收报警信息）
//        int  traceType = 2;
//        //实例化轨迹服务
//        trace = new Trace(getApplicationContext(), serviceId, entityName, traceType);
//        //实例化开启轨迹服务回调接口
//        OnStartTraceListener startTraceListener = new OnStartTraceListener() {
//            //开启轨迹服务回调接口（arg0 : 消息编码，arg1 : 消息内容，详情查看类参考）
//            @Override
//            public void onTraceCallback(int arg0, String arg1) {
//                System.out.println("---trace-->" + arg1);
//            }
//            //轨迹服务推送接口（用于接收服务端推送消息，arg0 : 消息类型，arg1 : 消息内容，详情查看类参考）
//            @Override
//            public void onTracePushCallback(byte arg0, String arg1) {
//                System.out.println("---trace push-->" + arg1);
//            }
//        };
//
//        //开启轨迹服务
//        client.setInterval(10, 60);//10s采集，60s发送
//        client.startTrace(trace, startTraceListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //实例化停止轨迹服务回调接口
        OnStopTraceListener stopTraceListener = new OnStopTraceListener(){
            // 轨迹服务停止成功
            @Override
            public void onStopTraceSuccess() {
                System.out.println("---GAME OVER--->");
            }
            // 轨迹服务停止失败（arg0 : 错误编码，arg1 : 消息内容，详情查看类参考）
            @Override
            public void onStopTraceFailed(int arg0, String arg1) {
                System.out.println("---trace failed-->" + arg1);
            }
        };

//停止轨迹服务
//        client.stopTrace(trace, stopTraceListener);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
//        newTime = System.currentTimeMillis();
//        if(newTime - oldTime < 300){
//            return;
//        }
//        oldTime = newTime;
        switch (checkedId){
            case R.id.rb_home_page:
//                hpi.back(topHeight,bottomHeight);
//                searchTop.setVisibility(View.VISIBLE);
                oldPos = newPos;
                newPos = 0;
//                replaceFragment(new BYFragment(1,new HomePageFragment1029()));
                changeTextColor(rb_home, rb_server, rb_custom, rb_my);
                repFragment(firstFrag,"first");
//                changeSelected(rb_home,rb_server,rb_custom,rb_my);
                break;
            case R.id.rb_service_station:
                oldPos = newPos;
                newPos = 1;
//                replaceFragment(new BYFragment(2,new ReduceFragment()));
                changeTextColor(rb_server, rb_home, rb_custom, rb_my);
                repFragment(secondFrag, "second");
//                changeSelected(rb_server, rb_home, rb_custom, rb_my);
//                searchTop.setVisibility(View.GONE);
                break;
            case R.id.rb_customer_service:
                oldPos = newPos;
                newPos = 2;
//                replaceFragment(new BYFragment(3,new CustomerServiceFragment()));
                changeTextColor(rb_custom, rb_server, rb_home, rb_my);
                repFragment(thirdFrag, "third");
//                changeSelected(rb_custom, rb_server, rb_home, rb_my);
//                searchTop.setVisibility(View.GONE);
                break;
            case R.id.rb_personal:
                sendBroadcast(new Intent("MyReceiver_Action"));
                oldPos = newPos;
                newPos = 3;
//                replaceFragment(new BYFragment(4, new PersonalFragment()));
                changeTextColor(rb_my, rb_server, rb_custom, rb_home);
                repFragment(fourthFrag,"fourth");
//                changeSelected(rb_my, rb_server, rb_custom, rb_home);
//                searchTop.setVisibility(View.GONE);
                break;
        }
    }

    private void changeSelected(RadioButton rb_home, RadioButton rb_server, RadioButton rb_custom, RadioButton rb_my) {
        rb_home.setSelected(true);
        rb_server.setSelected(false);
        rb_custom.setSelected(false);
        rb_my.setSelected(false);
    }

    private void changeTextColor(RadioButton rb1, RadioButton rb2, RadioButton rb3, RadioButton rb4) {
        rb1.setTextColor(0xfff08200);
        rb2.setTextColor(0xff234b64);
        rb3.setTextColor(0xff234b64);
        rb4.setTextColor(0xff234b64);
    }

    private void repFragment(Fragment fragment,String tag){
        FragmentTransaction ft = mFragmentManager.beginTransaction();

        if(!fragments.contains(fragment)){
            ft.add(R.id.main_container,fragment,tag);
            fragments.add(fragment);
        }
        for (Fragment f : fragments) {
            ft.hide(f);
        }
        ft.show(fragment);
        ft.commit();
    }

    /**
     * 替换fragment
     * @param fragment
     */
    private void replaceFragment(BYFragment fragment) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
//        if(newPos > oldPos) {
//            transaction.setCustomAnimations(R.anim.fragment_right_enter, R.anim.fragment_left_exit);
//        }else{
//            transaction.setCustomAnimations(R.anim.fragment_left_enter, R.anim.fragment_right_exit);
//        }

        if(!mFragments.contains(fragment)){
            System.out.println("---container-->" + fragment.toString());
            transaction.add(R.id.main_container,fragment.getFragment());
            mFragments.add(fragment);
        }
//        transaction.replace(R.id.main_container, fragment);

//        for (BYFragment f : mFragments) {
//            transaction.hide(f.getFragment());
//        }

        for (int i = 0; i < mFragments.size(); i++) {
            BYFragment byFragment = mFragments.get(i);
            if(byFragment.equals(fragment)){
                transaction.show(byFragment.getFragment());

            }else{
                transaction.hide(byFragment.getFragment());
            }
        }

        transaction.commitAllowingStateLoss();
    }

    @Override
    public void back() {
        ((RadioButton)mRadioGroup.getChildAt(0)).setChecked(true);
    }

    @Override
    public void onBackPressed() {
        switch (backFlag++){
            case 0:
                ToastUtils.showToast("再按一次，退出程序");
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        backFlag = 0;
                    }
                }, 3 * 1000);
                break;
            case 1:
                finish();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.home_page_search:
                Intent intent = new Intent(this, SearchActivity.class);
                intent.putExtra("search",et_search.getText().toString().trim());
                startActivity(intent);
                break;
        }
    }

    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
}
